package com.zb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.constant.WorkConstant;
import com.zb.entity.*;
import com.zb.extend.WorkNetworkExtend;
import com.zb.extend.WorkOrderExtend;
import com.zb.mapper.ZjWorkOrderMapper;
import com.zb.mobile.NetworkMobileOrderMessageListSelectVo;
import com.zb.mobile.NetworkOrderRecordSearchVo;
import com.zb.mobile.NetworkOrderStatSelectVo;
import com.zb.mobile.UserOrderSelectVo;
import com.zb.result.PageUtil;
import com.zb.service.*;
import com.zb.sms.entity.OrderReceiveVo;
import com.zb.sms.service.SmsSendMessageService;
import com.zb.utils.RandomUtil;
import com.zb.utils.ZbDateUtil;
import com.zb.utils.ZbOrderNoUtil;
import com.zb.view.ViewGoods;
import com.zb.view.ViewNetworkEmpDetail;
import com.zb.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static org.springframework.transaction.annotation.Isolation.READ_COMMITTED;

/**
 * <p>
 * 工单表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-09-20
 */
@Service
public class ZjWorkOrderServiceImpl extends ServiceImpl<ZjWorkOrderMapper, ZjWorkOrder> implements ZjWorkOrderService {
    @Resource
    private ZjWorkOrderMapper workOrderMapper;
    @Resource
    private ZjFactoryService factoryService;
    @Resource
    private ZjFactoryAccountBalanceService factoryAccountBalanceService;
    @Resource
    private ZjFactoryOrderModuleSettlementService factoryOrderModuleSettlementService;
    @Resource
    private ZjWorkDetailService workDetailService;
    @Resource
    private ZjWorkUserService workUserService;
    @Resource
    private ZjWorkGoodsService workGoodsService;
    @Resource
    private ZjWorkFieldValService workFieldValService;
    @Resource
    private ZjWorkModuleService workModuleService;
    @Resource
    private ZjWorkImageService workImageService;
    @Resource
    private ZjWorkClientStrategyService workClientStrategyService;
    @Resource
    private ViewGoodsService viewGoodsService;
    @Resource
    private ZjAccountService accountService;
    @Resource
    private ZjWorkReservationLogService workReservationLogService;
    @Resource
    private ZjNetworkModuleSettlementService networkModuleSettlementService;
    @Resource
    private ZjWorkDispatchNetworkService workDispatchNetworkService;
    @Resource
    private ZjNetworkService networkService;
    @Resource
    private ZjNetworkStrategyService networkStrategyService;
    @Resource
    private ViewNetworkEmpDetailService viewNetworkEmpDetailService;

    // 保存、修改工单
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public Map<String, Object> save(AccounLoginInfo loginInfo, boolean isUserMobileOrder, OrderVo orderVo, List<OrderGoodsVo> orderGoodsVos) {
        // 校验品牌商家是否存在
        ZjFactory factory = null;
        if (orderVo.getSource() == WorkConstant.WORK_SOURCE_7) {
            factory = factoryService.getById(orderVo.getFactoryId());
            Assert.notNull(factory, "品牌商家参数[ " + orderVo.getFactoryId() + " ]的数据不存在");
        }
        ZjWorkOrder order = new ZjWorkOrder();
        BeanUtils.copyProperties(orderVo, order);
        order.setFactoryId(null == order.getFactoryId()? 0L : order.getFactoryId());
        order.setUpdateEmpId(loginInfo.getId());
        order.setUpdateEmp(loginInfo.getName());
        ZjWorkModule module = workModuleService.getById(orderVo.getModuleId());

        ZjFactoryOrderModuleSettlement orderModuleSettlement = null;
        if (null != factory) {
            // 品牌商家结算价
            orderModuleSettlement = factoryOrderModuleSettlementService.getByFactoryIdAndModuleId(orderVo.getFactoryId(), orderVo.getModuleId());
        }
        order.setId(IdWorker.getId());
        order.setCustAccId(loginInfo.getCustAccId());
        order.setCode(ZbOrderNoUtil.orderNo(loginInfo.getCustAccId()));
        order.setArchived(false);
        order.setNewAdvance(0);
        order.setWaitCopeEvent(0);
        order.setReminderNum(0);
        order.setWarrantyDay(module.getWarrantyDay());
        order.setWorkLevelId(null == order.getWorkLevelId()? 0L : order.getWorkLevelId());
        order.setEndOrder(false);
        order.setSettlementStatus(WorkConstant.WORK_SETTLEMENT_STATUS_0);
        order.setWithdrawFreezeDay(0);
        order.setComment(false);
        order.setChangeOrder(false);
        order.setSuspendStatus(0);
        order.setFactoryRemark("");
        order.setCreateEmpType(1);
        order.setCreateFactory("");
        order.setCreateEmpId(loginInfo.getId());
        order.setCreateEmp(loginInfo.getName());
        order.setGmtCreate(new Date());
        order.setGmtUpdate(new Date());

        // 分配规则条件
        WorkDispatchConditionVo workDispatchConditionVo = null;
        if (module.getAutoDispatchClient() || module.getAutoDispatchNetwork()) {
            List<Long> goodsIds = orderGoodsVos.stream().map(OrderGoodsVo::getGoodsId).distinct().toList();
            List<Long> goodsSpecIds = orderGoodsVos.stream().map(OrderGoodsVo::getGoodsSpecId).distinct().toList();
            List<ViewGoods> viewGoodsList = viewGoodsService.getByGoodsIdsAndGoodsSpecIds(goodsIds, goodsSpecIds);

            workDispatchConditionVo = new WorkDispatchConditionVo()
                    .setId(module.getWorkClientStrategyId())
                    .setGoodsBrandIds(viewGoodsList.stream().map(ViewGoods::getBrandId).distinct().toList())
                    .setGoodsTypeIds(viewGoodsList.stream().map(ViewGoods::getTypeId).distinct().toList())
                    .setModuleId(module.getId())
                    .setProvince(orderVo.getOrderUser().getProvince())
                    .setCity(orderVo.getOrderUser().getCity())
                    .setArea(orderVo.getOrderUser().getArea())
                    .setTown(orderVo.getOrderUser().getTown());
        }
        List<WorkLogVo> serviceLogVos = new ArrayList<>();
        List<WorkLogVo> userMobileVos = new ArrayList<>();
        if (isUserMobileOrder) {
            userMobileVos.add(new WorkLogVo(loginInfo, order.getId(), "客户报单", "自助报单成功"));
        } else {
            serviceLogVos.add(new WorkLogVo(loginInfo, order.getId(), "系统客服报单", "工单创建成功"));
        }
        order.setNetworkId(null == order.getNetworkId()? 0L : order.getNetworkId());
        order.setEmpId(null == order.getEmpId()? 0L : order.getEmpId());

        // 手动指定客服，仅PC端报单
        if (order.getEmpId() > 0) {
            serviceLogVos.add(new WorkLogVo(loginInfo, order.getId(), "分配客服", "客服【" + accountService.getNameById(orderVo.getEmpId()) + "】正在处理中，等待分派服务商"));
        } else {
            // 自动分配客服
            if (module.getAutoDispatchClient()) {
                Long empId = workClientStrategyService.getEmpIdById(workDispatchConditionVo);
                order.setEmpId(empId);
                if (isUserMobileOrder) {
                    if (empId == 0) {
//                        serviceLogVos.add(new WorkLogVo(loginInfo.getCustAccId(), "系统", order.getId(), "自动分配客服", "【自动分配客服】分配失败，没有匹配到相应客服，请重新指定客服"));
                    } else {
                        serviceLogVos.add(new WorkLogVo(loginInfo.getCustAccId(), "系统", order.getId(),"自动分配客服",
                                "分配成功，工单客服【" + accountService.getNameById(empId) + "】正在处理中，等待分派服务商"));
                    }
                } else {
                    if (empId == 0) {
//                        serviceLogVos.add(new WorkLogVo(loginInfo, order.getId(), "自动分配客服", "【自动分配客服】分配失败，没有匹配到相应客服，请重新指定客服"));
                    } else {
                        serviceLogVos.add(new WorkLogVo(loginInfo, order.getId(), "自动分配客服",
                                "分配成功，客服【" + accountService.getNameById(empId) + "】正在处理中，等待分派服务商"));
                    }
                }
            } else {
//                if (isUserMobileOrder) {
//                    userMobileVos.add(new WorkLogVo(loginInfo, order.getId(), "自动分配客服", "当前模块已关闭自动分配客服，请重新指定客服"));
//                } else {
//                    serviceLogVos.add(new WorkLogVo(loginInfo, order.getId(), "自动分配客服","当前模块已关闭自动分配客服，请重新指定客服"));
//                }
            }
        }
        // 工程师
        order.setNetworkEmpId(0L);
        List<WorkLogVo> networkLogs = new ArrayList<>();
        // 服务商是否自动确认接单，默认为false
        boolean networkSureReceiveOrder = false;
        // 分配服务商
        if (order.getNetworkId() > 0) {
            ZjNetwork network = networkService.getById(order.getNetworkId());
            Assert.notNull(network, "当前工单指定派单的服务商数据不存在");
            serviceLogVos.add(new WorkLogVo(loginInfo, order.getId(),"手动指定分派服务商", "服务商【" + networkService.getNameById(orderVo.getNetworkId()) + "】，等待确认接单"));
//            if (network.getCategory() == NetworkConstant.CATEGORY_1) {
//                networkSureReceiveOrder = networkStrategyService.isAutoSureReceiveOrder(order.getNetworkId()).getAutoSureReceiveOrder();
//            }
            if (network.getTeamType() == 2) {
                ViewNetworkEmpDetail networkEmpDetail = viewNetworkEmpDetailService.getManagerByNetworkId(order.getNetworkId());
                networkLogs.add(new WorkLogVo(loginInfo.getCustAccId(), networkEmpDetail.getAccountName(), order.getId(),"服务商已确认接单", "服务商已自动确认接单并派单工程师"));
                order.setNetworkEmpId(networkEmpDetail.getId());
                networkLogs.add(new WorkLogVo(loginInfo.getCustAccId(), networkEmpDetail.getAccountName(), order.getId(),"工程师已确认接单"));
            } else {
                networkSureReceiveOrder = networkStrategyService.isAutoSureReceiveOrder(order.getNetworkId()).getAutoSureReceiveOrder();
                if (networkSureReceiveOrder) {
                    ViewNetworkEmpDetail networkEmpDetail = viewNetworkEmpDetailService.getManagerByNetworkId(order.getNetworkId());
                    networkLogs.add(new WorkLogVo(loginInfo.getCustAccId(), networkEmpDetail.getAccountName(), order.getId(),"服务商已确认接单"));
                }
            }
        } else {
            if (!module.getAutoDispatchNetwork()) {
//                serviceLogVos.add(new WorkLogVo(loginInfo, order.getId(),"自动分派服务商", "当前模块已关闭自动分派服务商，请工单客服手动指派服务商"));
            } else {
                // todo 按规则分派服务商
                order.setNetworkId(0L);
                if (isUserMobileOrder) {
//                    serviceLogVos.add(new WorkLogVo(loginInfo.getCustAccId(), "系统", order.getId(),"分派服务商", "自动分派服务商规则正在维护升级中，请手动分派"));
                } else {
//                    serviceLogVos.add(new WorkLogVo(loginInfo, order.getId(), "分派服务商", "自动分派服务商规则正在维护升级中，请手动分派"));
                }
            }
        }

        order.setStatus(order.getNetworkId() == 0? WorkConstant.WORK_STATUS_1 : networkSureReceiveOrder? WorkConstant.WORK_STATUS_3 : WorkConstant.WORK_STATUS_2);

        BigDecimal networkModulePrice = new BigDecimal("0.00");
        if (order.getNetworkId() > 0) {
            ZjNetworkModuleSettlement moduleSettlement = networkModuleSettlementService.getNetworkIdAndModuleId(order.getNetworkId(), order.getModuleId());
            if (null != moduleSettlement) networkModulePrice = moduleSettlement.getPrice();
        }
        order.setAssignEmp(order.getEmpId() > 0);
        order.setAllInclusiveFee(null == orderModuleSettlement || orderModuleSettlement.getAllInclusiveFee());
        order.setModulePrice(null != orderModuleSettlement? orderModuleSettlement.getPrice() : orderVo.getOverinsured()? module.getOutSourcingPrice() : module.getInSourcingPrice());
        order.setNetworkModulePrice(networkModulePrice);
        order.setCollectCustomerPrice(null == order.getCollectCustomerPrice()? new BigDecimal("0.00") : order.getCollectCustomerPrice());
        order.setFactorySettlementDeductionPrice(new BigDecimal("0.00"));
        order.setNetworkSettlementDeductionPrice(new BigDecimal("0.00"));
        QueryWrapper<ZjWorkOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", order.getCode());
        Assert.isTrue(this.getOne(queryWrapper) == null, "工单编号重复");
        this.save(order);

        ZjWorkDetail workDetail = new ZjWorkDetail();
        workDetail.setId(order.getId());
        workDetail.setCustAccId(loginInfo.getCustAccId());
        workDetail.setNoReviewApplyWorkFeeNum(0);
        workDetail.setNoReviewApplyWorkSpareNum(0);
        workDetail.setEndOrderApply(false);
        workDetail.setCancelOrderApply(false);
        workDetail.setChangeNetworkApply(false);
        workDetail.setDispatchEmpId(order.getNetworkId() == null || order.getNetworkId() ==0? 0L : loginInfo.getId());
        workDetail.setDispatchTime(order.getNetworkId() == null || order.getNetworkId() ==0? null : new Date());
        workDetail.setReservation(false);
        workDetail.setOneTypeId(null == orderVo.getOneTypeId()? 0L : orderVo.getOneTypeId());
        workDetail.setTwoTypeId(null == orderVo.getTwoTypeId()? 0L : orderVo.getTwoTypeId());
        workDetail.setThreeTypeId(null == orderVo.getThreeTypeId()? 0L : orderVo.getThreeTypeId());
        workDetail.setOneWayId(null == orderVo.getOneWayId()? 0L : orderVo.getOneWayId());
        workDetail.setTwoWayId(null == orderVo.getTwoWayId()? 0L : orderVo.getTwoWayId());
        workDetail.setThreeWayId(null == orderVo.getThreeWayId()? 0L : orderVo.getThreeWayId());
        workDetail.setContent(orderVo.getContent());
        workDetail.setStatementVerifCode(RandomUtil.randomNumber6());
        workDetail.setCollectCustomerPriceVoucher(null == orderVo.getCollectCustomerPriceVoucher()? "" : orderVo.getCollectCustomerPriceVoucher());
        workDetailService.save(workDetail);
        workImageService.save(loginInfo.getCustAccId(), order.getId(), orderVo.getImageVos(), orderVo.getDelImageIds());
        workUserService.save(loginInfo.getCustAccId(), order.getId(), orderVo.getOrderUser());
        workGoodsService.save(loginInfo.getCustAccId(), order.getId(), orderGoodsVos, orderVo.getDelOrderGoodsIds());
        workFieldValService.save(loginInfo.getCustAccId(), order.getId(), orderVo.getWorkFieldVal());
        workDispatchNetworkService.save(loginInfo.getCustAccId(), order.getId(), order.getNetworkId());
        if (null != orderVo.getFactoryId() && orderVo.getFactoryId() > 0) {
            // 冻结品牌商家的下单金额
            factoryAccountBalanceService.updateFreezePriceById(orderVo.getFactoryId(), order.getModulePrice());
        }
        WorkServiceLog.saveService(serviceLogVos);
        WorkServiceLog.saveOrderUser(userMobileVos);
        WorkServiceLog.saveNetwork(networkLogs);
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                // 发送短信
                SmsSendMessageService.sendNewOrder(loginInfo, WorkUtilService.getOrderReceive(order.getId()));
            }
        });
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("id", order.getId());
        resultMap.put("workNo", order.getCode());
        return resultMap;
    }

    // 根据工单ID集合获取历史工单（编码的历史工单）
    @Override
    public Page<ZjWorkOrder> PageGetHistoryOrder(List<Long> workIds, PageUtil pageUtil) {
        if (null == workIds || workIds.isEmpty()) {
            return new Page<ZjWorkOrder>();
        }
        PageUtil.setPageLimit(pageUtil);
        QueryWrapper<ZjWorkOrder> wrapper = new QueryWrapper<>();
        wrapper.select("id", "code", "status", "work_level_id" , "network_id" , "gmt_create", "gmt_update");
        wrapper.in("id", workIds);
        return this.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), wrapper);
    }

    // 获取工单列表状态数量
    @Override
    public OrderStatusQtyVo getOrderListStatusQty(Long custAccId) {
        OrderStatusQtyVo qtyVo = workOrderMapper.getOrderListStatusQty(custAccId);
        Long isPauseNbr = workOrderMapper.getIsPauseNbr();
        qtyVo.setIsPauseQty(isPauseNbr);
        Long isHsNbr = workOrderMapper.getIsHsNbr();
        qtyVo.setIsHsQty(isHsNbr);
        Long isHxNbr = workOrderMapper.getIsHxNbr();
        qtyVo.setIsHxQty(isHxNbr);
        return qtyVo;
    }

    // 获取工单列表ID数据
    @Override
    public List<Long> getOrderListIdsByPageSearch(Long custAccId, OrderListSelectVo selectVo) {
        return workOrderMapper.getOrderListIdsByPageSearch(custAccId, selectVo);
    }

    // 获取工单归档列表ID数据
    @Override
    public List<Long> getOrderArchivedListIdsByPageSearch(Long custAccId, OrderArchivedListSearchVo archivedListSearchVo) {
        return workOrderMapper.getOrderArchivedListIdsByPageSearch(custAccId, archivedListSearchVo);
    }

    // 根据商家ID获取归档工单的完成工单数量
    @Override
    public long getOrderArchivedOrderStatusQty(Long custAccId, Integer status) {
        return workOrderMapper.getOrderArchivedOrderStatusQty(custAccId, status);
    }

    // 获取工单列表数据
    @Override
    public List<WorkOrderExtend> getList(List<Long> ids, String orderBy) {
        if (CollectionUtil.isEmpty(ids)) {
            return new ArrayList<>();
        }
        List<WorkOrderExtend> extendList = workOrderMapper.getList(ids, orderBy);
        extendList.forEach(t -> {
            t.setServiceDay(ZbDateUtil.getDays(null != t.getEndTime()? t.getGmtCreate() : t.getGmtUpdate(), null != t.getEndTime()? t.getEndTime() : new Date()));
        });
        return extendList;
    }

    // 获取结算列表状态数量
    @Override
    public OrderSettlementStatusQtyVo getOrderSettlementStatusQty(Long custAccId) {
        return workOrderMapper.getOrderSettlementStatusQty(custAccId);
    }

    // 获取工单结算列表ID数据
    @Override
    public List<Long> getOrderSettlementListIdsByPageSearch(Long custAccId, OrderSettlementListSearchVo searchVo) {
        return workOrderMapper.getOrderSettlementListIdsByPageSearch(custAccId, searchVo);
    }

    // 获取工单结算列表ID数据总记录数
    @Override
    public long getOrderSettlementListCount(Long custAccId, OrderSettlementListSearchVo searchVo) {
        return workOrderMapper.getOrderSettlementListCount(custAccId, searchVo);
    }

    // 获取工单结算列表数据
    @Override
    public List<WorkOrderExtend> getOrderSettlementList(List<Long> ids, OrderSettlementListSearchVo searchVo) {
        List<WorkOrderExtend> extendList = workOrderMapper.getOrderSettlementList(ids, searchVo);
        extendList.forEach(t -> {
//            t.setServiceTime(ZbDateUtil.getTimeLength(null != t.getEndTime()? t.getGmtCreate() : t.getGmtUpdate(), null != t.getEndTime()? t.getEndTime() : new Date()));
            t.setServiceDay(ZbDateUtil.getDays(null != t.getEndTime()? t.getGmtCreate() : t.getGmtUpdate(), null != t.getEndTime()? t.getEndTime() : new Date()));
        });
        return extendList;
    }

    // 获取工单列表数据
    @Override
    public List<WorkOrderExtend> getOrderList(Long custAccId, OrderListSelectVo selectVo) {
        return workOrderMapper.getOrderList(custAccId, selectVo);

    }

    // 获取工单列表数据总记录数
    @Override
    public long getListCount(Long custAccId, OrderListSelectVo selectVo) {
        return workOrderMapper.getListCount(custAccId, selectVo);
    }

    // 获取工单归档列表数据总记录数
    @Override
    public long getOrderArchivedListCount(Long custAccId, OrderArchivedListSearchVo searchVo) {
        return workOrderMapper.getOrderArchivedListCount(custAccId, searchVo);
    }

    // 根据工单模块ID获取关联工单的模块ID
    @Override
    public List<Long> getRelationModuleIdByModuleIds(List<Long> moduleIds) {
        return workOrderMapper.getRelationModuleIdByModuleIds(moduleIds);
    }

    // 根据工单ID集合获取处理结束的工单
    @Override
    public List<ZjWorkOrder> getHandlerEndOrderByIds(List<Long> workIds) {
        if (null == workIds || workIds.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkOrder> wrapper = new QueryWrapper<>();
        wrapper.select("id", "code");
        wrapper.in("id", workIds)
                .in("status", WorkConstant.WORK_STATUS_4, WorkConstant.WORK_STATUS_5);
        return this.list(wrapper);
    }

    // 根据客服ID获取客服处理中的工单数量
    @Override
    public List<EmpOrderCountVo> getEmpOrderCountByEmpIds(List<Long> empIds) {
        if (CollectionUtil.isEmpty(empIds)) {
            return new ArrayList<>();
        }
        return workOrderMapper.getEmpOrderCountByEmpIds(empIds);
    }

    // 根据客服ID查询最后完成工单的客服ID（根据客服分配策略查询熟客客服ID）
    @Override
    public List<EmpOrderCountVo> getHistoryOrderLastEmpIdByEmpIds(List<Long> empIds) {
        return workOrderMapper.getHistoryOrderLastEmpIdByEmpIds(empIds);
    }

    // 批量分配客服
    @Override
    public void dispatchOrderEmp(AccounLoginInfo loginInfo, List<Long> workIds, Long empId) {
        Assert.isTrue(CollectionUtil.isNotEmpty(workIds), "必须要指定分配客服的工单");
        Assert.isTrue(null != empId, "必须指定要分配工单的客服");
        checkOrderStatus(workIds);

        QueryWrapper<ZjWorkOrder> wrapper = new QueryWrapper<>();
        wrapper.select("id", "code", "emp_id");
        wrapper.in("id", workIds);
        List<ZjWorkOrder> orderList = this.list(wrapper);
        List<ZjWorkOrder> orders = orderList.stream().filter(f -> f.getEmpId() > 0).toList();
        Assert.isTrue(CollectionUtil.isEmpty(orders), "工单单号[" + orders.stream().map(ZjWorkOrder::getCode).collect(Collectors.joining("、")) + "]的工单的已分配客服，不可重复分配客服流程");

        List<ZjWorkOrder> updateOrders = new ArrayList<>();
        List<WorkLogVo> logVos = new ArrayList<>();
        ZjWorkOrder order = null;
        for (Long id : workIds) {
            order = new ZjWorkOrder();
            order.setId(id);
            order.setAssignEmp(true);
            order.setEmpId(empId);
            order.setAssignEmpTime(new Date());
            order.setUpdateEmpId(loginInfo.getId());
            order.setUpdateEmp(loginInfo.getName());
            updateOrders.add(order);
            logVos.add(new WorkLogVo(loginInfo, id, "指定客服分配", "分配客服成功，客服正在处理"));
        }
        this.updateBatchById(updateOrders);
        WorkServiceLog.saveService(logVos);
    }

    // 检查工单是否处理中
    @Override
    public void checkOrderHandlerStatus(List<Long> workIds) {
        if (null == workIds || workIds.isEmpty()) {
            return;
        }
        QueryWrapper<ZjWorkOrder> wrapper = new QueryWrapper<>();
        wrapper.select("id", "code", "status");
        wrapper.in("id", workIds);
        List<ZjWorkOrder> orderList = this.list(wrapper);
        List<String> workNos = orderList.stream().filter(f -> f.getStatus() == WorkConstant.WORK_STATUS_1).map(ZjWorkOrder::getCode).toList();
        Assert.isTrue(CollectionUtil.isEmpty(workNos), "工单单号[" + String.join("、", workNos) + "]的工单处于【待客服确认】流程，不可跨流程操作");
    }

    // 检查工单是否处理中
    @Override
    public void checkOrderHandlerStatus(Long workId) {
        List<Long> workIds = new ArrayList<>();
        workIds.add(workId);
        checkOrderHandlerStatus(workIds);
    }

    // 检查工单状态
    @Override
    public void checkOrderStatus(List<Long> workIds) {
        if (null == workIds || workIds.isEmpty()) {
            return;
        }
        QueryWrapper<ZjWorkOrder> wrapper = new QueryWrapper<>();
        wrapper.select("id", "code", "status");
        wrapper.in("id", workIds);
        List<ZjWorkOrder> orderList = this.list(wrapper);
        List<String> workNos = orderList.stream().filter(f -> f.getStatus() == WorkConstant.WORK_STATUS_4).map(ZjWorkOrder::getCode).toList();
        Assert.isTrue(CollectionUtil.isEmpty(workNos), "工单单号[" + String.join("、", workNos) + "]的工单流程已完成，不可操作该工单");
        workNos = orderList.stream().filter(f -> f.getStatus() == WorkConstant.WORK_STATUS_5).map(ZjWorkOrder::getCode).toList();
        Assert.isTrue(CollectionUtil.isEmpty(workNos), "工单单号[" + String.join("、", workNos) + "]的工单流程已取消并结束，不可操作该工单");
    }

    // 检查工单状态
    @Override
    public void checkOrderStatus(Long workId) {
        List<Long> workIds = new ArrayList<>();
        workIds.add(workId);
        checkOrderStatus(workIds);
    }

    // 检查工单事件
    @Override
    public void checkOrderEvent(List<Long> workIds) {
        if (null == workIds || workIds.isEmpty()) {
            return;
        }
        QueryWrapper<ZjWorkOrder> wrapper = new QueryWrapper<>();
        wrapper.select("id", "code");
        wrapper.in("id", workIds);
        List<ZjWorkOrder> orderList = this.list(wrapper);

        QueryWrapper<ZjWorkDetail> detailQueryWrapper = new QueryWrapper<>();
        detailQueryWrapper.select("id", "no_review_apply_work_fee_num", "no_review_apply_work_spare_num", "is_end_order_apply AS endOrderApply", "is_cancel_order_apply AS cancelOrderApply", "is_change_network_apply AS changeNetworkApply");
        detailQueryWrapper.in("id", workIds);
        List<ZjWorkDetail> workDetails = workDetailService.list(detailQueryWrapper);
        // 服务费用
        List<String> workNos = workDetails.stream().filter(f -> f.getNoReviewApplyWorkFeeNum() > 0).map(detail -> {
            return orderList.stream().filter(of -> Objects.equals(of.getId(), detail.getId())).map(ZjWorkOrder::getCode).findFirst().get();
        }).toList();
        Assert.isTrue(CollectionUtil.isEmpty(workNos), "工单单号[" + String.join("、", workNos) + "]存在未审核的服务费用，不可操作该工单");
        // 工单备件
        workNos = workDetails.stream().filter(f -> f.getNoReviewApplyWorkSpareNum() > 0).map(detail -> {
            return orderList.stream().filter(of -> Objects.equals(of.getId(), detail.getId())).map(ZjWorkOrder::getCode).findFirst().get();
        }).toList();
        Assert.isTrue(CollectionUtil.isEmpty(workNos), "工单单号[" + String.join("、", workNos) + "]存在未审核的工单配件，不可操作该工单");
        // 结单申请
        workNos = workDetails.stream().filter(ZjWorkDetail::getEndOrderApply).map(detail -> {
            return orderList.stream().filter(of -> Objects.equals(of.getId(), detail.getId())).map(ZjWorkOrder::getCode).findFirst().get();
        }).toList();
        Assert.isTrue(CollectionUtil.isEmpty(workNos), "工单单号[" + String.join("、", workNos) + "]存在未审核的结单申请，不可操作该工单");
        // 取消工单申请
        workNos = workDetails.stream().filter(ZjWorkDetail::getCancelOrderApply).map(detail -> {
            return orderList.stream().filter(of -> Objects.equals(of.getId(), detail.getId())).map(ZjWorkOrder::getCode).findFirst().get();
        }).toList();
        Assert.isTrue(CollectionUtil.isEmpty(workNos), "工单单号[" + String.join("、", workNos) + "]存在未审核的结单申请，不可操作该工单");
        // 改派服务商申请
        workNos = workDetails.stream().filter(ZjWorkDetail::getChangeNetworkApply).map(detail -> {
            return orderList.stream().filter(of -> Objects.equals(of.getId(), detail.getId())).map(ZjWorkOrder::getCode).findFirst().get();
        }).toList();
        Assert.isTrue(CollectionUtil.isEmpty(workNos), "工单单号[" + String.join("、", workNos) + "]存在未审核的改派服务商申请，不可操作该工单");
    }

    // 检查工单事件
    @Override
    public void checkOrderEvent(Long workId) {
        List<Long> workIds = new ArrayList<>();
        workIds.add(workId);
        checkOrderEvent(workIds);
    }

    @Override
    public void checkIsDispatchOrder(List<Long> workIds) {
        if (CollectionUtil.isEmpty(workIds)) {
            return;
        }
        // 查询工单是否已派单服务商
        QueryWrapper<ZjWorkOrder> wrapper = new QueryWrapper<>();
        wrapper.select("id", "code", "network_id", "network_emp_id")
                .in("id", workIds);
        List<ZjWorkOrder> orderList = this.list(wrapper);
        // 已派单服务商
        List<ZjWorkOrder> dispatchNetworkOrders = orderList.stream().filter(f -> f.getNetworkId() > 0).toList();
        Assert.isTrue(CollectionUtil.isEmpty(dispatchNetworkOrders), "工单单号[ " + dispatchNetworkOrders.stream().map(ZjWorkOrder::getCode).collect(Collectors.joining("、")) +
                " ]的工单已派单到服务商，无法更新工单流程");
        // 已派工给工程师
        List<ZjWorkOrder> dispatchNetworkEmpOrders = orderList.stream().filter(f -> f.getNetworkEmpId() > 0).toList();
        Assert.isTrue(CollectionUtil.isEmpty(dispatchNetworkOrders), "工单单号[ " + dispatchNetworkEmpOrders.stream().map(ZjWorkOrder::getCode).collect(Collectors.joining("、")) +
                " ]的工单已派工给服务工程师，无法更新工单流程");
    }

    // 根据服务商ID获取所有工单数量
    @Override
    public List<QtyVo> getTotalOrderByNetworkIds(List<Long> networkIds) {
        if (CollectionUtils.isEmpty(networkIds)) {
            return new ArrayList<>();
        }
        return workOrderMapper.getTotalOrderByNetworkIds(networkIds);
    }

    // 根据服务商ID获取所有处理中工单数量
    @Override
    public List<QtyVo> getServiceOrderByNetworkIds(List<Long> networkIds) {
        if (CollectionUtils.isEmpty(networkIds)) {
            return new ArrayList<>();
        }
        return workOrderMapper.getServiceOrderByNetworkIds(networkIds);
    }

    // 获取服务商详情之工单明细列表
    @Override
    public List<ZjWorkOrder> getNetworkDetailOrderList(Long networkId, PageUtil pageUtil) {
        return workOrderMapper.getNetworkDetailOrderList(networkId, pageUtil);
    }

    // 获取服务商详情之工单明细列表
    @Override
    public long getNetworkDetailOrderListCount(Long networkId) {
        return workOrderMapper.getNetworkDetailOrderListCount(networkId);
    }

    // 根据服务商ID获取关联工单的服务商ID
    @Override
    public List<Long> getRelationNetworkIdByNetworkId(List<Long> networkIds) {
        if (CollectionUtils.isEmpty(networkIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkOrder> wrapper = new QueryWrapper<>();
        wrapper.select("network_id");
        wrapper.in("network_id", networkIds);
        wrapper.groupBy("network_id");
        wrapper.last("limit 10");
        return this.list(wrapper).stream().map(ZjWorkOrder::getNetworkId).toList();
    }

    // 根据工单ID获取关联的服务商
    @Override
    public List<WorkNetworkExtend> getNetworkByWorkIds(List<Long> workIds) {
        if (CollectionUtil.isEmpty(workIds)) {
            return new ArrayList<>();
        }
        return workOrderMapper.getNetworkByWorkIds(workIds);
    }

    // 根据移动端报单工单列表关键词搜索
    @Override
    public List<Long> getWorkIdByUserMobileSearch(Long custAccId, Long userId, UserOrderSelectVo selectVo) {
        return workOrderMapper.getWorkIdByUserMobileSearch(custAccId, userId, selectVo);
    }

    // 获取客户报单端工单列表
    @Override
    public List<WorkOrderExtend> getUserOrderList(Long custAccId, Long userId, List<Long> workIds, UserOrderSelectVo selectVo) {
        return workOrderMapper.getUserOrderList(custAccId, userId, workIds, selectVo);
    }

    // 获取客户报单端工单列表总记录数
    @Override
    public long getUserOrderListCount(Long custAccId, Long userId, List<Long> workIds, UserOrderSelectVo selectVo) {
        return workOrderMapper.getUserOrderListCount(custAccId, userId, workIds, selectVo);
    }

    // 获取移动端的历史工单
    @Override
    public List<ZjWorkOrder> getUserMobileHistoryOrder(Long custAccId, Long userId, List<Long> ids, SelectVo selectVo) {
        return workOrderMapper.getUserMobileHistoryOrder(custAccId, userId, ids, selectVo);
    }

    // 获取移动端的历史工单总记录数
    @Override
    public long getUserMobileHistoryOrderCount(Long custAccId, Long userId, List<Long> ids) {
        return workOrderMapper.getUserMobileHistoryOrderCount(custAccId, userId, ids);
    }

    // 获取服务商移动端工单报表(工单分析)
    @Override
    public List<DateQtyVo> getNetworkMobileWeekCreateOrderStat(Long custAccId, Long networkId, Long networkEmpId, boolean manager) {
        return workOrderMapper.getNetworkMobileWeekCreateOrderStat(custAccId, networkId, networkEmpId, manager);
    }

    // 获取服务商移动端工单报表(工单分析)
    @Override
    public List<DateQtyVo> getNetworkMobileWeekEndOrderStat(Long custAccId, Long networkId, Long networkEmpId, boolean manager) {
        return workOrderMapper.getNetworkMobileWeekEndOrderStat(custAccId, networkId, networkEmpId, manager);
    }

    // 获取工单报表(工单类型占比)
    @Override
    public List<QtyVo> getNetworkOrderModuleStat(Long networkId, NetworkOrderStatSelectVo selectVo) {
        return workOrderMapper.getNetworkOrderModuleStat(networkId, selectVo);
    }

    // 获取服务人员移动端创建工单统计数量
    @Override
    public List<DateQtyVo> getNetworkMobileCreateOrderStat(Long networkId, NetworkOrderStatSelectVo selectVo) {
        return workOrderMapper.getNetworkMobileCreateOrderStat(networkId, selectVo);
    }

    // 获取服务人员移动端工单结单统计数量
    @Override
    public List<DateQtyVo> getNetworkMobileFinishOrderStat(Long networkId, NetworkOrderStatSelectVo selectVo) {
        return workOrderMapper.getNetworkMobileFinishOrderStat(networkId, selectVo);
    }

    // 获取排行榜数据
    @Override
    public List<QtyVo> getNetworkFinishOrderScoreStat(Long networkId, NetworkOrderStatSelectVo selectVo) {
        return workOrderMapper.getNetworkFinishOrderScoreStat(networkId, selectVo);
    }

    // 获取服务商移动端消息工单列表
    @Override
    public List<WorkOrderExtend> getNetworkMobileOrderMessageList(Long networkId, Long networkEmpId, NetworkMobileOrderMessageListSelectVo selectVo) {
        return workOrderMapper.getNetworkMobileOrderMessageList(networkId, networkEmpId, selectVo);
    }

    // 获取服务商移动端消息工单列表总记录数
    @Override
    public long getNetworkMobileOrderMessageListCount(Long networkId, Long networkEmpId, NetworkMobileOrderMessageListSelectVo selectVo) {
        return workOrderMapper.getNetworkMobileOrderMessageListCount(networkId, networkEmpId, selectVo);
    }

    // 根据服务商ID&服务商人员ID获取服务人员的工单数量
    @Override
    public List<QtyVo> getNetworkEmpOrderQtyByNetworkAndNetworkEmpIds(Long networkId, List<Long> networkEmpIds) {
        return workOrderMapper.getNetworkEmpOrderQtyByNetworkAndNetworkEmpIds(networkId, networkEmpIds);
    }

    // 根据服务商搜索条件获取工单ID
    @Override
    public List<Long> getWorkIdByNetworkOrderMobileSearch(Long custAccId, Long networkId, Long networkEmpId, String keyword) {
        return workOrderMapper.getWorkIdByNetworkOrderMobileSearch(custAccId, networkId, networkEmpId, keyword);
    }

    // 根据工单ID更新新进展或待处理事件数量
    @Override
    public void updateNewAdvanceOrWaitCopeEventById(Long id, Integer newAdvance, Integer waitCopeEvent) {
        ZjWorkOrder order = new ZjWorkOrder();
        order.setId(id);
        order.setNewAdvance(newAdvance);
        if (null != waitCopeEvent) order.setWaitCopeEvent(waitCopeEvent);
        this.updateById(order);
    }

    // 根据工单ID获取工单导出字段
    @Override
    public List<WorkOrderExtend> getOrderExportFieldByIds(List<Long> ids, String orderBy) {
        if (CollectionUtil.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return workOrderMapper.getOrderExportFieldByIds(ids, orderBy);
    }

    // 根据[服务商ID] & [服务人员ID]获取今日完成工单量
    @Override
    public long getTodayFinishOrderQty(Long custAccId, Long networkId, Long networkEmpId) {
        return workOrderMapper.getTodayFinishOrderQty(custAccId, networkId, networkEmpId);
    }

    // 查询服务商移动端总工单数量
    @Override
    public long getNetworkMobileTotalOrderQty(Long custAccId, Long networkId, Long networkEmpId, NetworkOrderStatSelectVo selectVo) {
        return workOrderMapper.getNetworkMobileTotalOrderQty(custAccId, networkId, networkEmpId, selectVo);
    }

    // 获取服务商移动端完成工单数量
    @Override
    public long getNetworkMobileFinishOrderQty(Long custAccId, Long networkId, Long networkEmpId, NetworkOrderStatSelectVo selectVo) {
        return workOrderMapper.getNetworkMobileFinishOrderQty(custAccId, networkId, networkEmpId, selectVo);
    }

    // 获取服务商近七天(含今天)的工单数
    @Override
    public List<DateQtyVo> getNetworkInSevenDaysOrder(Long custAccId, Long networkId, Long networkEmpId) {
        return workOrderMapper.getNetworkInSevenDaysOrder(custAccId, networkId, networkEmpId);
    }

    @Override
    public void updateByChangeNetwork(AccounLoginInfo loginInfo, Long workId, Integer status, Long networkId, Long networkEmpId, BigDecimal modulePrice, BigDecimal totalPrice, BigDecimal payPrice) {
        ZjWorkOrder workOrder = new ZjWorkOrder();
        workOrder.setId(workId);
        workOrder.setStatus(status);
        workOrder.setNetworkId(networkId);
        workOrder.setNetworkEmpId(networkEmpId);
        workOrder.setNetworkModulePrice(null != modulePrice? modulePrice : new BigDecimal("0.00"));
        workOrder.setChangeOrder(true);
        workOrder.setNewAdvance(0);
        workOrder.setWaitCopeEvent(0);
        workOrder.setUpdateEmpId(loginInfo.getId());
        workOrder.setUpdateEmp(loginInfo.getName());
        this.updateById(workOrder);

        ZjWorkDetail workDetail = new ZjWorkDetail();
        workDetail.setId(workId);
        workDetail.setDispatchEmpId(loginInfo.getId());
        workDetail.setDispatchTime(new Date());
        workDetail.setReservation(false);
        workDetail.setReservationDate(null);
        workDetail.setReservationStartTime(null);
        workDetail.setReservationEndTime(null);
        workDetailService.updateById(workDetail);
    }

    // 获取待审核的工单事件
    @Override
    public List<WorkWaitCheckOrderEvent> getWaitCheckOrderEventByWorkId(Long workId) {
        return workOrderMapper.getWaitCheckOrderEventByWorkId(workId);
    }

    // 获取商家详情之工单列表
    @Override
    public List<WorkOrderExtend> getFactoryDetailOrderList(Long factoryId, PageUtil pageUtil) {
        return workOrderMapper.getFactoryDetailOrderList(factoryId, pageUtil);
    }

    // 获取商家详情之工单列表总记录数
    @Override
    public long getFactoryDetailOrderListCount(Long factoryId) {
        return workOrderMapper.getFactoryDetailOrderListCount(factoryId);
    }

    // 根据品牌商家ID获取工单所有费用(含：结算、工单服务费、工单配件费)
    @Override
    public BigDecimal getFactoryAllFeeById(Long id) {
        List<Long> ids = new ArrayList<>();
        ids.add(id);
        List<ZjWorkOrder> orderList = getFactoryAllFeeByIds(ids);
        return CollectionUtil.isEmpty(orderList)? new BigDecimal("0.0") : orderList.get(0).getModulePrice();
    }

    // 根据品工单ID获取工单所有费用(含：结算、工单服务费、工单配件费)
    @Override
    public List<ZjWorkOrder> getFactoryAllFeeByIds(List<Long> ids) {
        return workOrderMapper.getFactoryAllFeeById(ids);
    }

    // 查询重复工单并返回工单ID
    @Override
    public List<Long> getWorkRepeat(Long custAccId, WorkRepeatSearchVo search) {
        return workOrderMapper.getWorkRepeat(custAccId, search);
    }

    // 获取服务商移动端工单记录
    @Override
    public List<ZjWorkOrder> getMobileWithdrawOrderRecord(Long networkId, Long networkEmpId, NetworkOrderRecordSearchVo search) {
        return workOrderMapper.getMobileWithdrawOrderRecord(networkId, networkEmpId, search);
    }

    // 获取服务商移动端工单记录总记录数
    @Override
    public long getMobileWithdrawOrderRecordCount(Long networkId, Long networkEmpId, NetworkOrderRecordSearchVo search) {
        return workOrderMapper.getMobileWithdrawOrderRecordCount(networkId, networkEmpId, search);
    }

    // 根据工单ID获取服务商的所有费用
    @Override
    public List<QtyVo> getNetworkTotalFee(List<Long> workIds) {
        if (CollectionUtil.isEmpty(workIds)) {
            return new ArrayList<>();
        }
        List<QtyVo> networkTotalFee = workOrderMapper.getNetworkTotalFee(workIds);
        return networkTotalFee.stream().filter(Objects::nonNull).toList();
    }

    // 根据工单ID获取服务商的所有费用
    @Override
    public QtyVo getNetworkTotalFeeById(Long workId) {
        return workOrderMapper.getNetworkTotalFeeById(workId);
    }

    // 获取工单记录详情
    @Override
    public ZjWorkOrder getWithdrawOrderRecordDetail(Long workId) {
        return workOrderMapper.getWithdrawOrderRecordDetail(workId);
    }

    // 可提现工单列表
    @Override
    public List<WorkOrderExtend> getWithdrawOrderList(Long networkId, Long networkEmpId, NetworkOrderRecordSearchVo search) {
        return workOrderMapper.getWithdrawOrderList(networkId, networkEmpId, search);
    }

    // 可提现工单列表总记录数
    @Override
    public long getWithdrawOrderListCount(Long networkId, Long networkEmpId, NetworkOrderRecordSearchVo search) {
        return workOrderMapper.getWithdrawOrderListCount(networkId, networkEmpId, search);
    }

    // 根据服务商ID & 服务人员ID获取可提现金额
    @Override
    public BigDecimal getNetworkWithdrawMoney(Long networkId, Long networkEmpId) {
        List<ZjWorkOrder> orderList = workOrderMapper.getNetworkWithdrawMoney(networkId, networkEmpId);
        if (CollectionUtil.isEmpty(orderList)) {
            return new BigDecimal("0.00");
        }
        List<OrderSettlementPriceVo> settlementPriceVoList = getOrderSettlementPriceByWorkId(orderList.stream().map(ZjWorkOrder::getId).toList());
        BigDecimal totalPrice = new BigDecimal("0.00");
        for (ZjWorkOrder order : orderList) {
            totalPrice = totalPrice.add(order.getNetworkModulePrice()
                    .add(settlementPriceVoList.stream().filter(f -> Objects.equals(f.getWorkId(), order.getId())).findFirst().map(OrderSettlementPriceVo::getPayNetworkPrice).orElse(new BigDecimal("0.00")))
                    .subtract(order.getNetworkSettlementDeductionPrice()));
        }
        return totalPrice;
    }

    // 根据服务商ID & 服务人员ID获取冻结金额
    @Override
    public BigDecimal getNetworkFreezeMoney(Long networkId, Long networkEmpId) {
        List<ZjWorkOrder> orderList = workOrderMapper.getNetworkFreezeMoney(networkId, networkEmpId);
        if (CollectionUtil.isEmpty(orderList)) {
            return new BigDecimal("0.00");
        }
        List<OrderSettlementPriceVo> settlementPriceVoList = getOrderSettlementPriceByWorkId(orderList.stream().map(ZjWorkOrder::getId).toList());
        BigDecimal totalPrice = new BigDecimal("0.00");
        for (ZjWorkOrder order : orderList) {
            totalPrice = totalPrice.add(order.getNetworkModulePrice()
                    .add(settlementPriceVoList.stream().filter(f -> Objects.equals(f.getWorkId(), order.getId())).findFirst().map(OrderSettlementPriceVo::getPayNetworkPrice).orElse(new BigDecimal("0.00")))
                    .subtract(order.getNetworkSettlementDeductionPrice()));
        }
        return totalPrice;
    }

    // 查询工单单号是否重复
    @Override
    public Integer existCodeByCustAccId(Long custAccId, String workNo) {
        return workOrderMapper.existCodeByCustAccId(custAccId, workNo);
    }
    @Resource
    private ZjWorkSpareMaterialService workSpareMaterialService;
    @Resource
    private ZjWorkFeeDetailService workFeeDetailService;

    // 根据工单ID获取工单结算价
    @Override
    public List<OrderSettlementPriceVo> getOrderSettlementPriceByWorkId(List<Long> workIds) {
        if (CollectionUtil.isEmpty(workIds)) {
            return new ArrayList<>();
        }
        List<OrderSettlementPriceVo> orderSettlementPriceVos = new ArrayList<>();
        // 工单配件费
        List<ZjWorkSpareMaterial> spareMaterialList = workSpareMaterialService.getOrderSettlementFeeByWorkId(workIds);
        orderSettlementPriceVos.addAll(spareMaterialList.stream().map(spare -> {
            return new OrderSettlementPriceVo(spare.getWorkId(), spare.getPrice(), spare.getPayNetworkPrice(), spare.getReceiveFactoryPrice());
        }).toList());
        // 工单服务费
        List<ZjWorkFeeDetail> feeDetailList = workFeeDetailService.getOrderSettlementFeeByWorkId(workIds);
        if (CollectionUtil.isNotEmpty(feeDetailList)) {
            for (ZjWorkFeeDetail feeDetail : feeDetailList) {
                if (orderSettlementPriceVos.stream().anyMatch(f -> Objects.equals(f.getWorkId(), feeDetail.getWorkId()))) {
                    orderSettlementPriceVos.stream().filter(f -> Objects.equals(f.getWorkId(), feeDetail.getWorkId())).forEach(t -> {
                        t.setPrice(t.getPrice().add(feeDetail.getPrice()));
                        t.setReceiveFactoryPrice(t.getReceiveFactoryPrice().add(feeDetail.getReceiveFactoryPrice()));
                        t.setPayNetworkPrice(t.getPayNetworkPrice().add(feeDetail.getPayNetworkPrice()));
                    });
                    continue;
                }
                orderSettlementPriceVos.add(new OrderSettlementPriceVo(feeDetail.getWorkId(), feeDetail.getPrice(), feeDetail.getPayNetworkPrice(), feeDetail.getReceiveFactoryPrice()));
            }
        }
        return orderSettlementPriceVos;
    }

    // 根据工单ID获取工单结算价
    @Override
    public OrderSettlementPriceVo getOrderSettlementPriceByWorkId(Long workId) {
        List<Long> workIds = new ArrayList<>();
        workIds.add(workId);
        List<OrderSettlementPriceVo> settlementPriceVoList = getOrderSettlementPriceByWorkId(workIds);
        return CollectionUtil.isNotEmpty(settlementPriceVoList)? settlementPriceVoList.get(0) : null;
    }

    public Boolean QualityAccId (Long custAccId) {
        // 获取质保状态，返回值是 Long 类型
        Integer overinsuredStatus = workOrderMapper.QualityAccId(custAccId);

        // 判断质保状态，0 表示保内，1 表示保外
        if (overinsuredStatus != null && overinsuredStatus == 1) {
            return true;  // 保外
        } else {
            return false; // 保内
        }
    }

    @Override
    @Transactional
    public void updateInfo(OrderVo orderVo, AccounLoginInfo loginInfo) {
        if (StringUtils.isNotBlank(orderVo.getContent())){
            workOrderMapper.editOrderInfo(orderVo.getContent(), orderVo.getId());
        }
        if (orderVo.getIdList() != null) {
            List<WorkLogVo> logVos = new ArrayList<>();
            for (Long id : orderVo.getIdList()) {
                ZjWorkOrder zjWorkOrder = workOrderMapper.selectById(id);
                if (zjWorkOrder.getIsPause() == null) {
                    workOrderMapper.setOrderPause(1, id);
                }else if (zjWorkOrder.getIsPause().equals(0)){
                    workOrderMapper.setOrderPause(1, id);
                }else {
                    workOrderMapper.setOrderPause(0, id);
                }
                if (zjWorkOrder.getIsPause() == null || zjWorkOrder.getIsPause().equals(0)) {
                    logVos.add(new WorkLogVo(loginInfo, id, "暂挂工单", null));
                } else if (zjWorkOrder.getIsPause().equals(1)) {
                    logVos.add(new WorkLogVo(loginInfo, id, "解除工单暂挂", null));
                }
            }
            WorkServiceLog.saveService(logVos);
        }
        workOrderMapper.editUserInfo(orderVo);
    }
}
